import { Platform } from "react-native";

import { api_base as API_BASE_PATH, appname as AppName, appsecret as APP_SECRET } from '../config/common.json';

import {ksort, hex_md5} from './helpers';

export async function ajax_user(url, data){
    data = arguments[1] ? arguments[1] : {};
    data.uid = global.uid;
    data.token = global.token;
    return ajax_basic(url, data);
}

export async function ajax_basic(url, data = {}) {
    data["mm"] = global.vendor + " " + global.model + " " + global.oversion;
    data["macaddress"] = global.mac;
    data["_buvid"] = global.channel;
    data["imei"] = global.imei;
    data["_app"] = AppName;
    data["version_code"] = global.rversion;
    data["_timestamp"] = Date.parse(new Date());
    data["deviceSystemName"] = Platform.OS === "android" ? "android" : "ios";
    data = ksort(data);
    let data2 = [];
    let index = 0;
    for (let key in data) {
        data2[index] = key + "=" + data[key];
        index ++;
    }
    let post_str = encodeURIComponent(data2.join('&'));
    let sign = hex_md5(post_str + APP_SECRET);
    data2[index] = "sign=" + sign;
    post_str = data2.join("&");
    return fetch(API_BASE_PATH + url, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: post_str
        })
            .then(response => {
                return response.json();
            })
            .catch(error => {
                console.error(error);
            });
}